package ai.moran.test.header;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * @author haitao
 */
public class Customer {

    public static void main(String[] args) throws Exception {


        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("10.80.20.209");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("abm-order");
        connectionFactory.setUsername("dc_shop");
        connectionFactory.setPassword("JF8tga3#s3");

        //连接重试
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);
        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();
        //声明
        String exchangeName = "test_headers_exchange";
        String exchangeType = "headers";
        String queueName = "test_headers_queue";
        String routingKey = "";
        // 1 声明交换机
        channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
        // 2 声明队列
        channel.queueDeclare(queueName, false, false, false, null);
        // 3 建立交换机和队列的绑定关系:

        Map<String, Object> map = new Hashtable<>();
        map.put("x-match", "any");
        map.put("user", "wyt");
        map.put("code", "java");

        channel.queueBind(queueName, exchangeName, routingKey, map);

        //durable 是否持久化消息
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //参数：队列名称、是否自动ACK、Consumer
        channel.basicConsume(queueName, true, consumer);
        //循环获取消息  
        while (true) {
            //获取消息，如果没有消息，这一步将会一直阻塞  
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("收到消息：" + msg);
        }
    }
}
